package com.hunantv.mglive.ui.discovery.publisher.pic;


import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

import com.hunantv.mglive.utils.L;

//这个控件的作用是能让ViewPager按照最大孩子的高度进行排版
//默认在xml配置visibility为gone，代码中设置微visible的时候就不能进行wrap_content排版..
public class WrapContentHeightViewPager extends ViewPager {

	boolean mFirstLayout = true;
	public WrapContentHeightViewPager(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

	    int height = 0;
	    for(int i = 0; i < getChildCount(); i++) {
	        View child = getChildAt(i);
	        child.measure(widthMeasureSpec,heightMeasureSpec);
	        int h = child.getMeasuredHeight();
	        if(h > height) height = h;
	        
	    }

	    L.d("emoji", "getChildCount: " + getChildCount() + " child on Measure height:" + height);
	    
	    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);//在评估孩子节点高度之后，使用精确高度进行排版。。。

	    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	    
	    if(mFirstLayout){
	    	//因为是wrap content layout..再确定自己子控件的数量后（getChildCount ！＝ 0），需要重新排版一次
	    	this.post(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					WrapContentHeightViewPager.this.requestLayout();
				}
	    	});
	    	mFirstLayout = false;
	    }
	}
}
